// pages/paired_detail/paired_detail.js
const getToken = require('../../utils/get_token.js');
const getMemId = require('../../utils/memberId.js');
const WxParse = require('../../wxParse/wxParse.js');
let [goodId, tuanId, openId, memberId, pageNo] = ['', '', '', '', 1];
let cookie,token;
const ckToken = async (that) => {//token确认
  let nTime = Math.floor(new Date().getTime() / 1000);
  let oldTime = wx.getStorageSync('ntime') || 0;
  if (nTime < oldTime)//现在的时间小于到期时间
  {
    thou(that);
  } else {
    let tokens = await getToken.getToken();
    thou(that);
  }
}
const thou =async (that) => {//token没有失效时执行的代码
  if (openId == '') {
    getToken.getOpenId(function (res) {
      openId = res.data.openId;
      wx.setStorageSync('openId', res.data.openId);
      if (memberId == '') {
        getMemId.getMemId(res.data.openId, function (res) {
          if (res.data.flag == 'true') {
            wx.setStorageSync('memberId', res.data.memberId);
          } else {
            wx.redirectTo({ url: '../login/login?id=3&gid=' + goodId + '&tuanid=' + tuanId })
          }
         })
      }
    });
  } else {
    if (memberId == '') {
      wx.redirectTo({ url: '../login/login?id=3&gid=' + goodId + '&tuanid=' + tuanId })
    }
  }
  await getDeati(that);
  getA(that);
  likeList(that);
  getRule(that);
}
const getRule = (that) => {//规则
  let params = [ 'common/noteBook/getNoteBook', {"id":"7D484691DA9E488A863BFF7A8A0617B1"}]
  getToken.getData(function (res) {
    console.log(res.data)
    WxParse.wxParse('rule', 'html', res.data.content, that, 0);
  }, ...params)

};
const cTime = function (that, time) {
  let h = adzo(parseInt(time / 3600));
  let m = adzo(parseInt((time / 60) % 60));
  let s = adzo(parseInt(time % 60));
  time--;
  that.setData({
    house:h,
    minutes:m,
    seconds:s
  })
  setInterval(function () {
    if (time <= 0) {  
      that.data.times = '00:00:00';
      that.data.isShow=false;
    } else {
      h = adzo(parseInt(time / 3600));
      m = adzo(parseInt((time / 60) % 60));
      s = adzo(parseInt(time % 60));
      time--;
    }
    that.setData({
      isShow: that.data.isShow,
      house:h,
      minutes:m,
      seconds:s
    })
  }, 1000);
}
const adzo = function (num) {
  if (num < 10)
    return ('0' + num);
  else
    return num;
}
const getDeati = (that) => {//获取详情
  wx.request({
    header: { 'content-type': 'application/x-www-form-urlencoded' },
    method: 'POST',
    url: 'https://interface.globalhexi.cn/shop/pingTuan/getPinTuanNewDetail',
    data: { id: goodId },
    success: function (res) {
      console.log(res.data)
      let data=res.data;
      if(data.goodsSpecList.length>0)//购买规格展示，表示有规格 
			  {
          that.data.ggShow=true;//有规格
          for (let k = 0; k < data.goodsSpecList.length; k++)
          {
            that.data.SpecList[k] = { name: data.goodsSpecList[k].name, ul: [] };
            for (let t = 0; t < data.goodsSpecList[k].specificationValueList.length; t++) {
              that.data.SpecList[k].ul.push({ productId: data.goodsSpecList[k].specificationValueList[t].id, name:data.goodsSpecList[k].specificationValueList[t].name })
            }
          }  
          if(that.data.SpecList.length>=2){
            that.data.twogShow=true;//双规格
          }
        }
      let goods = res.data.result;
      goods.isGroupBuy=data.isGroupBuy;
      let Urls = JSON.parse(goods.goodsPinTuanVo.img);
      goods.imgSrc = `https://www.globalhexi.com/${Urls[0].path}/small/${Urls[0].id}.jpg`;
      that.data.limitNum=goods.goodsPinTuanVo.goodsPinTuanSetIntVo.limitNums;
      that.data.olist.push({'name': '拼团购买', 'classiy': 1,'img':goods.imgSrc,'gname':goods.goodsPinTuanVo.goodsName,'isbest':data.isBest,'twogShow':that.data.twogShow,'id': goods.goodsPinTuanVo.goodsPinTuanSetIntVo.id,'limit':that.data.limitNum,'zt': data.isGroupBuy});
      let article = goods.goodsPinTuanVo.desc.replace('/hexishop', 'http://image.globalhexi.com');
      WxParse.wxParse('article', 'html', article, that, 0);
      let query = wx.createSelectorQuery();
      let height ;
      query.select('.details').boundingClientRect(rect => {
        height = rect.height;
        if (height > that.data.wh)
        {
          that.data.mShow=true;
          that.setData({
            wh: that.data.wh+'px',
            mShow: that.data.mShow
          })
        }
      }).exec();
      if(data.isGroupBuy){
				if(data.goodsParentCategoryId=='A15EB4444BCC4237995950D653BBF7AE')
				{
					that.data.ztaddre='商家地址';
          that.data.ztadd='扫码点';
				}
			}
      that.setData({
        s: goods,
        ztaddre:that.data.ztaddre,
        ztadd:that.data.ztadd,
      })
    }
  })
};
const getA = (that) => {//获取团列表
  let params = ['shop/pingTuan/gtmll', {"tuanId":tuanId,"logo":false}]
  getToken.getData(function (res) {
    console.log(res.data)
    let datas = res.data;
    let creatime =datas.endTime;

    datas.needPayPay = datas.needPayPay / 100;
    datas.price=(datas.intPinPrice/100).toFixed(2);
    if(datas.pinTuanSetPrice==null)//商品已下架
			{
        that.data.isShow=false;
        that.data.tName='商品已下架';
			}else{
        let all = 0, aOll = [],aNum=0;
        all=datas.rows.reduce(function(pre,cur){return cur.buyCount+pre },0)//获取总人数
        for (let i = 0; i < datas.rows.length; i++) {
          if (datas.rows[i].logo.indexOf('http') == -1) {
              datas.rows[i].logo = 'http://www.globalhexi.com/' + datas.rows[i].logo;
          }
          if (datas.rows[i].logo.match(/hexishop/g)) {
            datas.rows[i].logo= '/upload/head/default.png';
          }
          for (let j = 0; j < datas.rows[i].buyCount; j++) {
            aOll.push(datas.rows[i].logo);
            aNum++;
            if(aNum>=100){
              break;
            }
          }
        }
        that.data.aList=aOll;
        datas.tuanMemberNums = all + datas.lastNum;	             		
        datas.address = JSON.parse(datas.address);
        datas.cityName = datas.address.areaStore + datas.address.address;
        if (datas.state == 0)//还能参团
        {
          let Time = new Date();
          let getTime = Time.getTime();
          let sTime = (creatime - getTime) / 1000;
          cTime(that, sTime);
        } else {//拼团成功,拼团失败  
          that.data.nopShow = false;
          that.data.isShow = false;
        }
			}
    that.data.re = datas;
    that.setData({
      aList: that.data.aList,
      re: that.data.re,
      more: that.data.more,
      isShow: that.data.isShow,
      tName: that.data.tName,
      nopShow: that.data.nopShow
    })
  }, ...params)
};

const likeList = (that) => {//猜你喜欢
  if (that.data.boolT) {
    that.setData({hidden: false})
    that.data.boolT=false;
    let params = ['shop/pingTuan/guessYouLike', {"openId":openId,"memberId":memberId,"pageSize":pageNo,"seeType":2,"pinTuanGoodsId": goodId,"orderSn":""}]
    getToken.getData(function (res) {
      console.log(res.data)
      let data = res.data;
      if (data.rows.length > 0) {
        for (let i = 0; i < data.rows.length; i++) {
          //data.rows[i].goodsImageStore = data.rows[i].goodsImageStore.substring(1, data.rows[i].goodsImageStore.length - 1);
          data.rows[i].goodsImageStore = JSON.parse(data.rows[i].goodsImageStore);
          data.rows[i].img = 'https://www.globalhexi.com/' + data.rows[i].goodsImageStore[0].path + '/big/' + data.rows[i].goodsImageStore[0].id + '.jpg';
          data.rows[i].intPinPrice = (data.rows[i].intPinPrice / 100).toFixed(2);
          data.rows[i].intPrice = (data.rows[i].intPrice / 100).toFixed(2);
          that.data.lkList.push(data.rows[i]);
        }
      }
      setTimeout(function () {
        that.setData({
          lkList: that.data.lkList,
          hidden: true
        })
        that.data.boolT = true;
      }, 500)
    }, ...params)

  }
};
const getOneTemp=function(that,arr){//有1个规格时寻找临时数组
  that.data.tempList=[];
  arr.forEach(function(ele,index,arr){
      ele.name=ele.speciValueStoreList[0].name;
      that.data.tempList.push(ele)
  })
  that.setData({tempList:that.data.tempList})
}
const mnum=function(that,arr){//临时区间数组，将数量设置为0 
  that.data.tallList=[];
  arr.forEach(function(ele,index,arr){
     ele.num=0;
     ele.price=(ele.intPinPrice/100).toFixed(2);
     that.data.tallList.push(ele)
  })
  that.setData({tallList:that.data.tallList});
}
const changeSpe=function(that,productId){//有2个规格时寻找临时数组
  for(let i=0;i<that.data.SpecList[1].ul.length;i++){
     if(productId==that.data.SpecList[1].ul[i].productId){
        that.data.SpecList[1].ul[i].show=true;
        that.data.tempList=[];//临时数组
        that.data.tallList.forEach(function(ele,index,arr){
          if(productId==ele.speciValueStoreList[0].id){              
            ele.name=ele.speciValueStoreList[1].name;
              that.data.tempList.push(ele)
          }
          if(productId==ele.speciValueStoreList[1].id){
            ele.name=ele.speciValueStoreList[0].name;
            that.data.tempList.push(ele)
          }
        })
       }else{
        that.data.SpecList[1].ul[i].show=false;
       } 
  }
  that.setData({
    tempList:that.data.tempList,
    SpecList:that.data.SpecList
  })
}
const initialization=function(that,obj){//商品设置初始值
  that.data.storeNum=obj.store;
  if(obj.minNum<=that.data.storeNum)
  {
     mnum(that,obj.tuanSetProductList)//临时区间数组所有规格
    if (that.data.ggShow)//是否有规格
    {  
        if(that.data.twogShow){
        changeSpe(that,that.data.SpecList[1].ul[0].productId);
        }else{//单规格取临时数组
        getOneTemp(that,that.data.tallList)
        }
    }else{//无规格
      that.data.tallList[0].num=1;
      that.data.tempList=that.data.tallList;
      that.data.tempList[0].name='购买数量';
      that.setData({tempList:that.data.tempList})
    }
    that.data.allNum = that.data.tallList.reduce(function (prev, cur) {
      return cur.num + prev;
   }, 0); 
   that.data.allMoney = that.data.tallList.reduce(function (prev, cur) {
    let oMoney=(cur.intPinPrice/100)*cur.num;
    return oMoney + prev;
  }, 0);
  that.data.allMoney=that.data.allMoney.toFixed(2);
    that.setData({
      storeNum:that.data.storeNum,
      allMoney:that.data.allMoney,
      allNum:that.data.allNum
    })
  }
}
const jia=function(that,id,limit){//数量加事件 limit是限制的值，
  let num=0,iIndex=0;
  that.data.allNum = that.data.tallList.reduce(function (prev, cur) {
     return cur.num + prev;
  }, 0); 
  that.data.tallList.forEach(function(ele,index,arr){
    if(id==ele.id){
      iIndex=index;
    }else{
      ele.num=0
    }
  })
  that.data.allNum = that.data.tallList[iIndex].num;
  if(limit>that.data.allNum){
      that.data.tallList[iIndex].num+=1;
      that.data.allNum+=1;
      num=that.data.tallList[iIndex].num;
    for(let j=0;j<that.data.tempList.length;j++){
      if(id==that.data.tempList[j].id){
         that.data.tempList[j].num=num;
      }else{
         that.data.tempList[j].num=0;
      }
    }
    that.data.allMoney=num*(that.data.tallList[iIndex].intPinPrice/100);
    that.data.allMoney=that.data.allMoney.toFixed(2);
    that.setData({
      tallList:that.data.tallList,
      tempList:that.data.tempList,
      allMoney:that.data.allMoney,
      allNum:that.data.allNum
    })
  }
}
const jian=function(that,id,limit){//数量加事件 limit是限制的最小值，
  let num=0;
  that.data.allNum = that.data.tallList.reduce(function (prev, cur) {
     return cur.num + prev;
  }, 0); 
  if(limit<that.data.allNum){
    for(let i=0;i<that.data.tallList.length;i++){
      if(id==that.data.tallList[i].id){
         if(that.data.tallList[i].num>0){
          that.data.tallList[i].num-=1;
          that.data.allNum-=1;
         }
         num=that.data.tallList[i].num;
      }
    }
    for(let j=0;j<that.data.tempList.length;j++){
      if(id==that.data.tempList[j].id){
        that.data.tempList[j].num=num;
      }
    }
    that.data.allMoney = that.data.tallList.reduce(function (prev, cur) {
      let oMoney=(cur.intPinPrice/100)*cur.num;
      return oMoney + prev;
    }, 0);
    that.data.allMoney=that.data.allMoney.toFixed(2);
    that.setData({
      tallList:that.data.tallList,
      tempList:that.data.tempList,
      allMoney:that.data.allMoney,
      allNum:that.data.allNum
    })
  }
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nopShow:true,
    more: true,
    boolT: true,
    boxShow: true,
    store:0,
    price:'',
    aList:[],
    dList:[],
    lkList:[],
    wh:'auto',
    ztaddre:'自提地址',
    ztadd:'自提点',
    tName:'拼团已结束',
    mShow:false,
    isShow:true,
    ggShow:false,
    hidden: false,
    house:'00',
    minutes:'00',
    seconds:'00',
    animationSpeMenu:{},
    storeNum:0,
    allMoney:0,
    allNum:0,
    olist:[],
    tempList:[],
    SpecList:[],
    tallList:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    goodId = options.id;
    console.log(goodId)
    tuanId = options.tuanid;
    memberId = wx.getStorageSync('memberId') || '';
    openId = wx.getStorageSync('openId') || '';
    cookie = wx.getStorageSync('cookie') || '';
    token = wx.getStorageSync('token') || '';
    wx.getSystemInfo({
      success(res) {
        that.data.wh = res.windowHeight-20;
      }
    })
     // 初始化动画变量
     let animation = wx.createAnimation({
      duration: 500,
      transformOrigin: "50% 50%",
      timingFunction: 'ease',
    })
    that.animation = animation;
    ckToken(that);
  },
  // 执行规格动画
  startSpeAnimation: function (isShow) {
    let that = this
    if (isShow) {
      // vh是用来表示尺寸的单位，高度全屏是100vh
      that.animation.translateY(0 + 'vh').step()
    } else {
      that.animation.translateY(45 + 'vh').step()
    }
    that.setData({
      animationSpeMenu: that.animation.export(),
      cgShow:isShow
    })
  },
  // 点击规格选择取消按钮 
  hidespeSelected: function (e) {
    this.startSpeAnimation(false)
  },
  onShow: function () {

  },
  go_detail: function (e) {//直接去详情
    let that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      wx.navigateTo({
        url: '../paired_detail/paired_detail?scene=' + goodId,
        success: function () {
          setTimeout(function () {
            that.data.boolT = true;
          }, 500)
        }
      })
    }
  },
  goIndex: function (e) {
    let that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      wx.reLaunch({
        url: '../index/index',
        success: function () {
          setTimeout(function () {
            that.data.boolT = true;
          }, 500)
        }
      })

    }
  },
  jiaC(e){//参团数量加事件
    let that = this;
    let id = e.currentTarget.dataset.id;
    let limit=that.data.re.lastNum;
    if(that.data.limitNum>0){//商品有购买限制
      limit=that.data.limitNum;
    }
    jia(that,id,limit)
  },
  jianC(e){//参团数量减事件
    let that = this;
    let id = e.currentTarget.dataset.id;
    jian(that,id,1);
  },
  join: function (e) {//参团
    let that = this;
    initialization(that,that.data.re.pinTuanSetPrice)
    that.startSpeAnimation(true);
  },

  ctbuy:function(e){//弹窗参团
    let that = this;
    if(that.data.allNum>0){
      let pood=that.data.olist[0];
      pood.tallList=that.data.tallList;//已选货品数组
      pood.allNum=that.data.allNum;//已经选择的总份数
      pood.allMoney=that.data.allMoney;//已经选择的总计钱
      pood.lastNum=that.data.re.lastNum;//剩余份数
      pood.store=that.data.storeNum;//已经选择的区间库存
      pood.pinId=that.data.s.goodsPinTuanVo.id;
      wx.setStorageSync('ctpood', pood);
      if (that.data.boolT) {
        that.data.boolT = false;
        wx.navigateTo({
          url: '../pairedk_order/pairedk_order?tuanId=' + tuanId,
          success: function () {
            that.data.timer =setTimeout(function () {that.data.boolT = true;}, 500)
          }
        })
      }  
    }else{
      wx.showToast({title:'请选择商品购买数量',icon:'none',duration: 2000})
    }     
  },
  o_more:function(e){
    let that = this;
    that.setData({
      wh: 'auto',
      mShow: false
    })
  },
  enter: function (e) {
    let that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      wx.redirectTo({
        url: '../paired_detail/paired_detail?scene=' + e.currentTarget.dataset.id,
        success: function () {
          setTimeout(function () {
            that.data.boolT = true;
          }, 500)
        }
      })
    }
  },
  onReachBottom: function () {
    let that = this;
    pageNo++;
    likeList(that);
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let that = this;
    let tit='【仅剩' + that.data.re.lastNum + '个】我' + that.data.re.needPayPay + '元拼了' + that.data.s.goodsPinTuanVo.goodsName;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res)
    }
    return {
      title: tit,
      imageUrl: that.data.s.imgSrc,
      path: '/pages/tuxedo/tuxedo?id=' + goodId + '&tuanid=' + tuanId,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }

  }
})